package com.hejia.bulbul.controller;

import com.hejia.alauda.entity.Page;
import com.hejia.alauda.entity.PageCategory;
import com.hejia.alauda.entity.PageTemplate;
import com.hejia.alauda.entity.example.PageCategoryExample;
import com.hejia.alauda.entity.example.PageExample;
import com.hejia.alauda.entity.example.PageTemplateExample;
import com.hejia.alauda.searcher.PageCategorySearcher;
import com.hejia.alauda.searcher.PageSearcher;
import com.hejia.alauda.searcher.PageTemplateSearcher;
import com.hejia.alauda.service.PageService;
import com.hejia.alauda.utils.Pager;
import com.hejia.bulbul.entity.DataTablesReturnObject;
import com.hejia.bulbul.entity.JSONParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@Controller
@RequestMapping("page")
public class PagerController extends BaseController {

	private static final Log Logger = LogFactory
			.getLog(FinancialAssetController.class);

	@Resource
	private PageService pageService;

	/**
	 * page 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String pageList(Pager<Page> pager, PageSearcher searcher, Model model) {
		pageService.findAllPager(pager, (PageExample) searcher.getExample());
		model.addAttribute("page", pager);
		return "page/list";
	}

	/**
	 * page 列表
	 */
	@RequestMapping(value = "/list/ajax", method = RequestMethod.POST)
	@ResponseBody
	public DataTablesReturnObject<Page> pageListAsAjax(
			@RequestBody JSONParam[] params) {
		HashMap<String, String> paramMap = JSONParam.convertToMap(params);

		// 分页信息
		Pager<Page> pager = new Pager<Page>();
		int start = Integer.parseInt(paramMap.get("iDisplayStart"));
		int length = Integer.parseInt(paramMap.get("iDisplayLength"));
		pager.setPageSize(length);
		pager.setPageNumber(start / length + 1);

		// 查询条件
		PageExample exp = new PageExample();

		String sSearch = paramMap.get("sSearch");
		if (StringUtils.isNotEmpty(sSearch)) {
			exp.appendCriterion("name like  ", "%" + sSearch + "%");
		}
		// 排序
		int iSortingCols = Integer.parseInt(paramMap.get("iSortingCols"));
		for (int i = 0; i < iSortingCols; i++) {
			String iSortCol = paramMap.get("iSortCol_" + i);
			String mDataProp = paramMap.get("mDataProp_" + iSortCol);
			String sSortDir = paramMap.get("sSortDir_" + i);
			if (i > 0) {
				exp.setOrderByClause(exp.getOrderByClause() + ",");
				exp.setOrderByClause(exp.getOrderByClause() + mDataProp + " "
						+ sSortDir);
			} else {
				exp.setOrderByClause(mDataProp + " " + sSortDir);
			}
		}

		pageService.findAllPager(pager, exp);

		DataTablesReturnObject<Page> dtr = new DataTablesReturnObject<Page>(
				pager.getTotalCount(), paramMap.get("sEcho"), pager.getList());
		return dtr;
	}

	/**
	 * page 进入添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String pageAdd(ModelMap model) {
		model.addAttribute("parentPageCategories",
				pageService.findAllPageCategory());
		model.addAttribute("pageTemplate", pageService.findAllPageTemplate());
		model.put("addorexit", "addorexit");
		return "page/input";
	}

	/**
	 * page 保存
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String pageAddSave(Page page, ModelMap model,
			RedirectAttributes redirectAttributes) {
		try {
			if (pageService.findPageByName(page.getName()) != null) {
				redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
				redirectAttributes.addFlashAttribute("msg", "URL重复，添加失败");
				return "redirect:/page/list";
			}
			if (page.getContent().length() > 110000) {
				model.put("error", "内容字数超出限制");
				model.put("page", page);
				model.put("addorexit", "addorexit");
				model.addAttribute("parentPageCategories",
						pageService.findAllPageCategory());
				model.addAttribute("pageTemplate",
						pageService.findAllPageTemplate());
				if (page.getPageCategory() != null
						|| page.getPageCategory().getId() != null) {
					page.setPageCategory(pageService.findPageCategoryById(page
							.getPageCategory().getId()));
				}
				return "page/input";
			}
			page.setCreateDate(new Date());
			if (pageService.savePage(page)) {
				redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
				redirectAttributes.addFlashAttribute("msg", "页面添加成功");
			} else {
				redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
				redirectAttributes.addFlashAttribute("msg", "页面添加失败");
			}
			return "redirect:/page/list";
		} catch (Exception e) {
			Logger.error("添加页面失败", e);
			model.put("error", "添加页面失败 " + e.getMessage());
			model.put("page", page);
			model.put("addorexit", "addorexit");
			model.addAttribute("parentPageCategories",
					pageService.findAllPageCategory());
			model.addAttribute("pageTemplate",
					pageService.findAllPageTemplate());
			if (page.getPageCategory() != null
					|| page.getPageCategory().getId() != null) {
				page.setPageCategory(pageService.findPageCategoryById(page
						.getPageCategory().getId()));
			}
			return "page/input";
		}
	}

	/**
	 * page urlname检查是否重复
	 */
	@RequestMapping(value = "/name", method = RequestMethod.GET)
	public String pageUrlName(String name, Model model) {
		Page page = pageService.findPageByName(name);
		if (page != null) {
			model.addAttribute("status", STATUS_FAILD);
		} else {
			model.addAttribute("status", STATUS_SUCCESS);
		}
		return null;
	}

	/**
	 * page 详情页面
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String pageDetail(@PathVariable Long id, Model model) {
		Page page = pageService.findPageById(id);
		model.addAttribute("page", page);
		model.addAttribute("parentPageCategories",
				pageService.findAllPageCategory());
		model.addAttribute("pageTemplate", pageService.findAllPageTemplate());
		return "page/input";
	}

	/**
	 * page 修改
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String pageUpdate(Page page, Model model,
			RedirectAttributes redirectAttributes) {
		Page p = pageService.findPageByName(page.getName());

		if (p != null && p.getId().longValue() != page.getId().longValue()) {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "URL重复，修改失败");
			return "redirect:/page/list";
		}
		if (pageService.updatePage(page)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "页面修改成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "页面修改失败");
		}
		return "redirect:/page/list";
	}

	/**
	 * page 发布
	 */
	@RequestMapping(value = "/publish/{id}", method = RequestMethod.GET)
	public String pagePublish(@PathVariable Long id, Model model,
			RedirectAttributes redirectAttributes) {
		Page page = pageService.findPageById(id);
		page.setPublished(true);
		if (pageService.updatePage(page)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "页面修改成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "页面修改失败");
		}
		return "redirect:/page/list";
	}

	/**
	 * page 删除
	 */
	@RequestMapping(value = "/delete/{id}")
	public String pageDelete(@PathVariable Long id, Model model,
			RedirectAttributes redirectAttributes) {
		if (pageService.deletePage(id)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "页面删除成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "页面删除失败");
		}
		return "redirect:/page/list";
	}

	/**
	 * pageCategory 列表
	 */
	@RequestMapping(value = "/category/list", method = RequestMethod.GET)
	public String pageCategoryList(Pager<PageCategory> pager,
			PageCategorySearcher searcher, Model model) {
		pager.setPageSize(5);
		// 暂时使用对大类进行假分页
		pager = pageService.findAllPageCategory(pager,
				(PageCategoryExample) searcher.getExample());
		model.addAttribute("page", pager);
		return "page/category_list";
	}

	/**
	 * pageCategory 进入添加
	 * 
	 * @return
	 */
	@RequestMapping(value = "/category/add/{pid}", method = RequestMethod.GET)
	public String pageCategoryAdd(@PathVariable String pid, Model model,
			RedirectAttributes redirectAttributes) {
		Pager<PageCategory> pager = new Pager<PageCategory>();
		pager = pageService.findAllPageCategory(pager, null);
		model.addAttribute("list", pager);
		model.addAttribute("pid", pid);
		return "page/category_input";
	}

	/**
	 * pageCategory 保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "/category/save", method = RequestMethod.POST)
	public String pageCategorySave(PageCategory category, Model model,
			RedirectAttributes redirectAttributes) {
		if (category.getId() == null) {
			category.setCreateDate(new Date());
			pageService.savePageCategory(category);
			redirectAttributes.addFlashAttribute("msg",
					"分类" + category.getName() + "添加成功");
		} else {
			pageService.updatePageCategory(category);
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg",
					"分类" + category.getName() + "修改成功");
		}
		return "redirect:/page/category/list";
	}

	/**
	 * pageCategory 进入修改
	 * 
	 * @return
	 */
	@RequestMapping(value = "/category/update/{id}", method = RequestMethod.GET)
	public String pageCategoryShowUpdate(@PathVariable String id, ModelMap model) {
		Pager<PageCategory> pager = new Pager<PageCategory>();
		pager = pageService.findAllPageCategory(pager, null);
		model.addAttribute("list", pager);
		PageCategory category = pageService.findPageCategoryById(new Long(id));
		model.addAttribute("category", category);
		return "page/category_input";
	}

	/**
	 * pageCategory 修改
	 * 
	 * @return
	 */
	@RequestMapping(value = "/category/update", method = RequestMethod.PUT)
	public String pageCategoryUpdate(PageCategory category, Model model,
			RedirectAttributes redirectAttributes) {
		if (category.getId() != null) {
			pageService.updatePageCategory(category);
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg",
					"分类" + category.getName() + "修改成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "分类添加失败");
		}
		return "redirect:/page/category/list";
	}

	/**
	 * pageTemplate列表
	 */
	@RequestMapping(value = "/template/list", method = RequestMethod.GET)
	public String pageTemplateList(Pager<PageTemplate> pager,
			PageTemplateSearcher searcher, Model model) {
		pager = pageService.findAllPageTemplate(pager,
				(PageTemplateExample) searcher.getExample());
		model.addAttribute("page", pager);
		return "page/template_list";
	}

	/**
	 * pageTemplate 进入添加
	 */
	@RequestMapping(value = "/template/add", method = RequestMethod.GET)
	public String pageTemplateAdd(Model model) {
		return "page/template_input";
	}

	/**
	 * pageTemplate 保存
	 */
	@RequestMapping(value = "/template/add", method = RequestMethod.POST)
	public String pageTemplateAddSave(PageTemplate pageTemplate, Model model,
			RedirectAttributes redirectAttributes) {
		pageTemplate.setCreateDate(new Date());
		if (pageService.savePageTemplate(pageTemplate)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "模板添加成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "模板添加失败");
		}
		return "redirect:/page/template/list";
	}

	/**
	 * pageTemplate 编辑
	 */
	@RequestMapping(value = "/template/update", method = RequestMethod.POST)
	public String pageTemplateUpdate(PageTemplate pageTemplate, Model model,
			RedirectAttributes redirectAttributes) {
		if (pageService.updatePageTemplate(pageTemplate)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "模板修改成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "模板修改失败");
		}
		return "redirect:/page/template/list";
	}

	/**
	 * pageTemplate 进入 详情
	 */
	@RequestMapping(value = "/template/{id}")
	public String pageTemplate(@PathVariable Long id, Model model) {
		model.addAttribute("pageTemplate", pageService.findPageTemplateById(id));
		return "page/template_input";
	}

}
